package com.jiangyao.aop;

import com.jiangyao.common.utils.Util;
import com.jiangyao.model.entity.SysLog;
import com.jiangyao.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class SysLogAop {

	/**
	 * 当前线程请求开始时间
	 */
	private static final ThreadLocal<Long> REQUEST_START_TIME_THREAD_LOCAL = new ThreadLocal<>();

	@Autowired
	private SysLogService sysLogService;


	@Pointcut("execution(public * com.jiangyao.controller.*.*(..))")
	public void sysLog() {

	}

	@Before("sysLog()")
	public void doBefore(JoinPoint joinPoint) {
		// 请求开始时间  当前线程存放
		REQUEST_START_TIME_THREAD_LOCAL.set(System.currentTimeMillis());
	}

	@AfterReturning(returning = "ret", pointcut = "sysLog()")
	public void doAfterReturning(JoinPoint joinPoint, Object ret) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		String ip = Util.getIpAddr();

		Object[] args = joinPoint.getArgs();
		String parameter = "";
		for (Object argItem : args) {
			if (argItem != null && !(argItem instanceof BindingResult || argItem instanceof MultipartFile)) {
				parameter += argItem.toString();
			}
		}
		// 获取请求开始时间
		long startTime = REQUEST_START_TIME_THREAD_LOCAL.get();
		long runtime = System.currentTimeMillis() - startTime;

		// 获取请求开始时间
		SysLog sysLog = new SysLog();
		// 获取后台登录用户ID
//		AdminUserSessionVO adminUserSessionVO = ((SysLogServiceImpl)sysLogService).getAdminLoginSession();
//		if (adminUserSessionVO != null) {
//			sysLog.setUserId(adminUserSessionVO.getUid().longValue());
//		}
		sysLog.setUrl(request.getRequestURL().toString());
		sysLog.setIp(ip);
		sysLog.setRequest(parameter);
		sysLog.setResponse(ret != null ? ret.toString() : "");
		sysLog.setRuntime((int) runtime);
		sysLog.setCreateTime(new Date());
		// 异步保存日志
		sysLogService.asyncSaveSysLog(sysLog);
		// REQUEST_START_TIME_THREAD_LOCAL.remove();
	}

}
